package control
{
	import event.SendMessageEvent;
	import event.SendNameEvent;
	
	import model.ChatbotModel;
	import model.entity.Message;
	import model.entity.QueryResults;
	
	import mx.collections.ArrayCollection;
	
	import org.apache.solr.common.SolrDocumentList;
	import org.apache.solr.common.utils.NamedList;
	import org.apache.solr.common.utils.NamedListEntry;
	import org.apache.solr.solras.SolrClient;
	import org.apache.solr.solras.SolrQuery;
	import org.apache.solr.solras.SolrResponse;
	
	import service.ChatbotService;

	public class ChatbotController
	{
		protected var _chatbotModel:ChatbotModel;
		public function set chatbotModel(value:ChatbotModel):void
		{
			_chatbotModel = value;
		}
		
		protected var _chatbotService:ChatbotService;
		public function set chatbotService(value:ChatbotService):void
		{
			_chatbotService = value;
		}
		
		public function handleSendName(e:SendNameEvent):void
		{
			_chatbotModel.userName = e.name;
			
			var botFirst:Message = new Message();
			botFirst.agent = false;
			botFirst.alpha = 1;
			botFirst.text = 'Hello, ' + _chatbotModel.userName +
				'! I\'m here to answer all your questions about people I\'ve heard of, places I\'ve been and things I know about. ' +
				'My job is to know everything, but I often doubt myself. ' +
				'Why don\'t you spent some time and ask me a question?';
			_chatbotModel.messages.addItem(botFirst);
			_chatbotModel.chatHistory.addItem(botFirst);
			refreshChat();
		}
		
		
		public function handleSendMessage(e:SendMessageEvent):void
		{
			var botmsg:Message = new Message();
			
			if(e.message)
			{
				var msg:Message = new Message();
				msg.agent = true;
				msg.alpha = 1;
				msg.text = e.message;
				_chatbotModel.messages.addItem(msg);
				_chatbotModel.chatHistory.addItem(msg);
				refreshChat();
				
				var input:String = e.message;
				
				if(isQuestion(input))
				{
					_chatbotModel.messages.getItemAt(_chatbotModel.messages.length - 1).question = true;
					input = inputClear(input);
					if(input)
					{
						var client:SolrClient = new SolrClient("http://localhost:8983/solr");
						var q:SolrQuery = new SolrQuery('attr_content:'+ input);
						var solrResponse:SolrResponse = client.query(q, searchResultHandler);
					}	
					else
					{
						botmsg.agent = false;
						botmsg.text = 'Did you say something?';
						_chatbotModel.messages.addItem(botmsg);
						_chatbotModel.chatHistory.addItem(botmsg);
						refreshChat();
					}
				}
				else
				{
					switch (isPositive(input))
					{
						case "positive":
						{
							botmsg.agent = false;
							botmsg.text = _chatbotModel.positiveAnswers.getItemAt(genRandomNumber(0, _chatbotModel.positiveAnswers.length - 1)) as String;
							_chatbotModel.messages.addItem(botmsg);
							_chatbotModel.chatHistory.addItem(botmsg);
							refreshChat();
							setRating(1);
							break;
						}
						case "negative":
						{
							botmsg.agent = false;
							botmsg.text = _chatbotModel.negativeAnswers.getItemAt(genRandomNumber(0, _chatbotModel.negativeAnswers.length - 1)) as String;
							_chatbotModel.messages.addItem(botmsg);
							_chatbotModel.chatHistory.addItem(botmsg);
							refreshChat();
							setRating(2);
							break;
						}
						case "neutral":
						default:
						{
							botmsg.agent = false;
							botmsg.text = _chatbotModel.neutralAnswers.getItemAt(genRandomNumber(0, _chatbotModel.neutralAnswers.length - 1)) as String;
							_chatbotModel.messages.addItem(botmsg);
							_chatbotModel.chatHistory.addItem(botmsg);
							refreshChat();
							setRating(3);
							break;
						}
					}
				}
				
			}
			else 
			{
				botmsg.agent = false;
				botmsg.text = 'Did you say something?';
				_chatbotModel.messages.addItem(botmsg);
				_chatbotModel.chatHistory.addItem(botmsg);
				refreshChat();
			}
			
		}
		
		protected function searchResultHandler(solrResponse:SolrResponse):void 
		{
			var successfullQuery:Boolean = false;
			var queryResult:QueryResults = new QueryResults();
			
			//a lot of stupid parsing going on here
			var textArray:Array = new Array();
			var input:String;
			var solrDoc:SolrDocumentList = solrResponse.response.getValue("response") as SolrDocumentList;
			var docsArray:Array = solrDoc.documents.toString().split('SolrDocument\[\{attr_content=').concat();
			while(docsArray.length > 1)
			{
				textArray = docsArray.pop().toString().split(',attr_').reverse().concat();
				input = textArray.pop().toString();
				queryResult.results.addItem(input);
				queryResult.counter++;
			}
			
			var botmsg:Message = new Message();
			botmsg.agent = false;
			
			if (queryResult.results.length > 0)
			{
				successfullQuery = true;
				botmsg.text = queryResult.results.getItemAt(queryResult.results.length - 1).toString();
			}
			else
			{
				botmsg.text = _chatbotModel.sorryAnswers.getItemAt(genRandomNumber(0, _chatbotModel.sorryAnswers.length - 1)) as String;
			}
			_chatbotModel.messages.addItem(botmsg);
			_chatbotModel.chatHistory.addItem(botmsg);
			refreshChat();
			
			if (successfullQuery)
			{
				var botquestion:Message = new Message();
				botquestion.agent = false;
				botquestion.text = _chatbotModel.questionAnswers.getItemAt(genRandomNumber(0, _chatbotModel.questionAnswers.length - 1)) as String;
				_chatbotModel.messages.addItem(botquestion);
				_chatbotModel.chatHistory.addItem(botquestion);
				refreshChat();
			}
		}
		
		private function refreshChat():void
		{
			if (_chatbotModel.messages.length > 9)
			{
				_chatbotModel.messages.removeItemAt(0);
			}
			var diff:int = 10 - _chatbotModel.messages.length;
			for(var i:int = 0; i < _chatbotModel.messages.length; i++)
			{
				_chatbotModel.messages.getItemAt(i).alpha = (i + diff + 1) / 10;
			}
		}
		
		private function genRandomNumber(min:int, max:int):int
		{			
			return Math.round(Math.random() * (max - min) + min);
		}
		
		private function inputClear(input:String):String
		{
			var clearedInput:String = "";
			var isIn:Boolean;
			var inputArray:Array = new Array();
			input = input.replace(_chatbotModel.symbolPattern, "").replace(_chatbotModel.questionWord, "").replace(_chatbotModel.multiSpace, " ").replace(_chatbotModel.spaceAtEnd, "").replace(_chatbotModel.spaceAtBeg, "");
			inputArray = input.split(" ");
			while (inputArray.length > 0)
			{
				var str:String = inputArray.pop() as String
				for each (var arrayItem:String in _chatbotModel.stopWords)
				{
					if(str == arrayItem) 
					{
						isIn = true;
						break;
					}
				}
				if(!isIn) 
				{
					clearedInput = clearedInput.concat(str, " ");
				} 
			}
			return clearedInput;
			
		}
		
		private function isQuestion(input:String):Boolean
		{
			if (input.search(_chatbotModel.questionMark) != -1 || input.search(_chatbotModel.questionWord) != -1)
			{
				return true;
			}
			else return false;
		}
		
		private function isPositive(input:String):String
		{
			if (input.search(_chatbotModel.positive) != -1)
				return "positive";
			else if (input.search(_chatbotModel.negative) != -1)
				return "negative";
			else return "neutral";
		}
		
		private function setRating(type:Number):void
		{
			if(_chatbotModel.messages.length > 4)
			{
				if (_chatbotModel.messages.getItemAt(_chatbotModel.messages.length - 5).question == true)
				{
					_chatbotModel.messages.getItemAt(_chatbotModel.messages.length - 4).rating = type;
				}
			}
		}
		

	}
}